package com.cx.base.day19_thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * Cyclebarrier是一个支持并发的循环计数器，和countdownlatch有着很大不同，
 * 如下代码，通过await()方法减-，减到0自动置为2继续执行
 *
 * @Author: robert.song
 * @Date: Created in 2021/11/27
 */
@Slf4j
public class Thread_15_3_CyclicBarrier {
    public static void main(String[] args) {

        ExecutorService service = Executors.newFixedThreadPool(2);
//        线程池数最后和任务数保持一致
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
            log.info("task1,task2 finished...");
        });
        for (int i = 0; i < 3; i++) {
            service.submit(() -> {
                log.info("task1 begin...");
                try {
                    Thread.sleep(10000);
                    cyclicBarrier.await();  //2-1=1
                    log.info("task1 end...");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });

            service.submit(() -> {
                log.info("task2 begin...");
                try {
                    Thread.sleep(10000);
                    cyclicBarrier.await();  //1-1=0 ，当任务剩余0，所有线程从执行await()后的阻塞态恢复继续执行，如果有for循环任务自动恢复为2并执行，优点：相比countdownlatch,避免了重复创建任务对象
                    log.info("task2 end...");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }

        service.shutdown();
    }

}
